import 'dart:async';

import 'package:gameplay_flutter/lib_baseview/utils/cache_util.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/lib_network/http_api.dart';
import 'package:gameplay_flutter/lib_network/http_helper.dart';
import 'package:get/get.dart';

import '../lib_basemodel/user/user.dart';

class UserManager {
  static const TAG = "UserManager";

  //单例
  static final UserManager instance = UserManager._();
  final _controller = StreamController<User?>.broadcast();
  User? _currentUser;
  // 修改为
  final Rxn<String> _token = Rxn<String>();


  UserManager._() {}

  Stream<User?> listenUser() {
    return _controller.stream;
  }

// 改为
  String? get token => _token.value;

  void setToken(String? token) {
    _token.value = token;
  }

  // String cacheKey =
  // CacheKeys.userLoginCountCacheKey((user.id).toString());

  // String loginCountCacheKey(){
  //   return CacheKeys.userLoginCountCacheKey((user.id).toString());
  // }

// 修改 hasLogin() 方法
  bool hasLogin() {
    return _currentUser != null && _token.value?.isNotEmpty == true;
  }

  // int get currentUid => _currentUser?.userId;
  int get currentUid => _currentUser?.userId ?? 0;

  /// 用户ID 类似：2060690
  int get id => _currentUser?.id ?? 0;

  User? get currentUser => _currentUser ?? User();

  void updateUserInfo(User? userInfo) {
    // RLog.d("$TAG updateUserInfo:${userInfo?.toProto3Json()}");
    // RLog.d("$TAG updateUserInfoStack:${StackTrace.current.traceInfo}");
    _currentUser = userInfo;
    if (userInfo == null || userInfo.userCode == 0) {
      _token.value = null; // 替换 _token = null;
    } else {
      if (_currentUser!.gender != null) {
        // _currentUser!.gender = UserConstants.genderMan;
      }
    }
    setToken(userInfo?.token);
    _controller.sink.add(userInfo);

    if (userInfo != null) {
      final imUserName = _currentUser?.imId ?? '';
      final imPassword = _currentUser?.imPsw ?? '';
      final seconds = ImManager.of.isInitialized ? 0 : 1;
      Future.delayed(Duration(seconds: seconds), () {
        ImManager.of.signIn(username: imUserName, password: imPassword).then(
          (value) {
            if (!value) return;
            ImManager.of.updateUserInfo(
              nickname: userInfo.nickname,
              gender: userInfo.gender,
              avatarUrl: userInfo.headPortraitsUrl,
            );
          },
        );
      });
    }
  }

  void _imLogin() {}

  Future<bool> refreshUserInfo() async {
    return true;
    // BaseRspResult result = await UserApi.instance.getUserInfo();
    // if (result.isSuccess && result.data is UserInfoRsp) {
    //   updateUserInfo(result.data!.user);
    // }
    // return result.isSuccess;
  }

  /// 新增方法：增加登录次数
  /// keys: login_count_用户id
  Future<void> incrementLoginCount(String keys) async {
    int prefs = await getLoginCount(keys);
    prefs++;
    await CacheUtil.setInt(keys, prefs);
  }

  // 新增方法：清除登录次数
  Future<void> clearLoginCount(String keys) async {
    CacheUtil.delete(keys);
  }

  // 新增方法：获取登录次数
  Future<int> getLoginCount(String keys) async {
    // CacheUtil.CacheKeys

    final prefs = CacheUtil.getInt(keys);
    return prefs;
  }

  /// isLogoutResp：true 需要调用退出接口 false：不用调用退出接口
  logout({bool? isLogoutResp}) async {
    if (isLogoutResp ?? true) {
      var resp = await HttpHelper.instance().post(
        HttpApi.logout,
        showLoading: true,
        showToast: true,
        // body:
      );
    }

    // 清除当前用户信息
    _currentUser = null;

    // 清除令牌
    _token.value = null;

    // 清除登录次数
    if (_currentUser != null) {
      final keys =
          CacheKeys.userLoginCountCacheKey(_currentUser!.id.toString());
      clearLoginCount(keys);
    }

    // 添加其他需要清理的数据或操作
    // 例如：清除缓存、注销IM等

    // 通知监听者用户已登出
    _controller.sink.add(null);

    // 注销IM
    ImManager.of.signOut();

    CacheUtil.clear();
  }
}
